<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\Department;
use App\Models\Staff;
use Auth;
use Illuminate\Http\Request;

class DepartmentController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */

    private $user_id;
    private $ids;
    public function __construct()
    {
        $ids = [];
        $this->user_id = Auth::id();
        $root = Department::where('parentId', '=', null)->first();
        $child = Department::where(
            ['userId' => $this->user_id, 'depth' => 1])->first();
        if (empty($child)) {
            $child = Department::create(['name' => '组织结构', 'userId' => $this->user_id]);
            $child->makeChildOf($root);
        }
        $childs = $child->getDescendantsAndSelf(['id as deptId']);
        //子节点
        $this->ids = $childs;
    }
    /**
     * 查询所有
     */
    public function all(Request $request)
    {
        $root = Department::where(['userId' => $this->user_id, 'depth' => 1])->first();
        $count = ($root->rgt - $root->lft - 1) / 2;
        $company = Company::where('userId', $this->user_id)->first();
        $dep_tree[0]['id'] = $root->id;
        if (!empty($company)) {
            $dep_tree[0]['label'] = $company->cmpName;
        } else {
            $dep_tree[0]['label'] = $root->name;
        }
        $dep_tree[0]['people'] = $this->get_node_count($root->id);
        $get_node = Department::find($root->id);
        $node2 = $get_node->getDescendants(1, ['id', 'name as label'])->toArray();
        if (!empty($node2)) {
            $dep_tree[0]['level'] = 1;
        } else {
            $dep_tree[0]['level'] = 0;
        }
        $total_count = staff::whereIn('deptId', $this->ids)->where('status', 0)->count('id');
        $data['id'] = $root->id;
        $data['name'] = $root->name;
        $data['total_count'] = $total_count;
        $data['dep_count'] = $count;
        return $this->respond('get_ok', ['dept' => $dep_tree, 'root' => $data]);
    }

    private function get_node_count($id)
    {
        $total_count = 0;
        $node = Department::find($id);
        $id_str = $node->getDescendantsAndSelf(['id as deptId']);
        $total_count = staff::whereIn('deptId', $id_str)->where('status', 0)->count('id');
        return $total_count;
    }
    //获取部门员工信息
    public function get($id, $flag)
    {
        $type = [1, 2];
        if (!in_array($flag, $type)) {
            return $this->respond('empty_error');
        }
        $node = Department::find($id);
        $node2 = $node->getDescendants(1, ['id', 'name as label']);
        $data = [];
        $tree_node = $node2;
        if (!empty($node2->toArray())) {
            foreach ($node2 as $k => $val) {
                $tree_node[$k]['people'] = $this->get_node_count($val->id);
                $get_node = Department::find($val->id);
                $nodes = $get_node->getDescendants(1, ['id', 'name as label'])->toArray();
                if (!empty($nodes)) {
                    $tree_node[$k]['level'] = 1;
                } else {
                    $tree_node[$k]['level'] = 0;
                }
            }
        }
        $staff = Staff::where('deptId', $id)->where('status', 0)->select('id', 'name', 'mobile')->orderBy('id','desc')->get();
        $data['dept'] = $tree_node;
        if ($flag == 1) {
            $data['staff'] = $staff;
        }
        return $this->respond('get_ok', $data);
    }
    //新增保存
    public function add(Request $request)
    {
        $name = $request->input('name');
        $parentId = $request->input('parentId');
        if (empty($name) || empty($parentId)) {
            return $this->respond('empty_error');
        }
        $pnode = Department::where('id', $parentId)->first();
        if (empty($pnode)) {
            return $this->respond('get_error');
        }
        $node = Department::create(['name' => $name, 'userId' => $this->user_id]);
        $result = $node->makeChildOf($pnode);
        if ($result) {
            return $this->respond('add_ok');
        }
        return $this->respond('add_error');
    }
    //更新保存
    public function put(Request $request, $id)
    {
        if (empty($id)) {
            return $this->respond('empty_error');
        }
        $m = new Department();
        $model = $m::find($id);
        if (empty($model)) {
            return $this->respond('get_error');
        }
        $name = $request->input('name');
        if (empty($name)) {
            return $this->respond('empty_error');
        }
        $model->name = $name;
        $result = $model->save();
        if ($result) {
            return $this->respond('update_ok');
        }
        return $this->respond('update_error');
    }
    //删除
    public function remove($id)
    {
        if (empty($id)) {
            return $this->respond('empty_error');
        }
        $m = new Department();
        $model = $m::find($id);
        if (empty($model)) {
            return $this->respond('get_error');
        }
        $child_dep = Department::where('parentId', $id)->first();
        if (!empty($child_dep)) {
            return response()->json(['code' => '500', 'msg' => '请先删除当前部门下面的子部门']);
        }
        $staff = Staff::where('deptId', $id)->where('status', 0)->first();
        if (!empty($staff)) {
            return response()->json(['code' => '500', 'msg' => '请先删除当前部门下面的员工']);
        }
        $result = $model->delete();
        if ($result) {
            return $this->respond('delete_ok');
        }
        return $this->respond('delete_error');
    }
}
